import React, { useState, useEffect } from "react";
import { ConstructionSchemeAPI } from "@/api/ConstructionScheme";
import { CrossingPointAPI } from "@/api/CrossingPoint";
import { ProjectAPI } from "@/api/project";
import { useLocation, useNavigate } from "react-router-dom";
import { createPageUrl } from "@/utils";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { ArrowLeft, ArrowRight, Download } from "lucide-react";
import WizardHeader from "../components/scheme-wizard/WizardHeader";
import ProjectInfoStep from "../components/scheme-wizard/ProjectInfoStep";
import MeasurementDataStep from "../components/scheme-wizard/MeasurementDataStep";
import ConstructionMethodStep from "../components/scheme-wizard/ConstructionMethodStep";
import SchemeDetailStep from "../components/scheme-wizard/SchemeDetailStep";
import PreviewConfirmStep from "../components/scheme-wizard/PreviewConfirmStep";

export default function SchemeWizard() {
  const [currentStep, setCurrentStep] = useState(1);
  const [schemeData, setSchemeData] = useState({
    // 项目信息
    projectName: "",
    location: "",
    crossingType: "",
    voltageLevel: "220kV",
    constructionUnit: "",
    designUnit: "",
    supervisionUnit: "",
    startDate: "",
    endDate: "",

    // 测量数据
    spanLength: "",
    crossingHeight: "",
    groundClearance: "",
    windSpeed: "",
    iceThickness: "",
    temperatureMin: "",
    temperatureMax: "",
    soilCondition: "",
    terrainDescription: "",

    // 施工方法
    constructionMethod: "",
    methodReasoning: "",

    // 方案细节
    constructionSteps: [],

    // 其他信息
    crossingPointId: "",
    name: "",
    version: "1.0",
  });

  const [crossingPoints, setCrossingPoints] = useState([]);
  const [projects, setProjects] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const location = useLocation();
  const navigate = useNavigate();

  useEffect(() => {
    loadInitialData();
  }, []);

  const loadInitialData = async () => {
    try {
      const [pointsData, projectsData] = await Promise.all([
        CrossingPointAPI.getList(),
        ProjectAPI.getList(),
      ]);

      setCrossingPoints(pointsData.data);
      setProjects(projectsData.data);

      // 检查URL参数，预填充数据
      const urlParams = new URLSearchParams(location.search);
      const crossingPointId = urlParams.get("crossingPointId");
      if (crossingPointId) {
        const point = pointsData.data.find((p) => p.id === crossingPointId);
        if (point) {
          const project = projectsData.data.find(
            (p) => p.id === point.projectId
          );
          setSchemeData((prev) => ({
            ...prev,
            crossingPointId: point.id,
            projectName: project?.name || "",
            location: point.crossingObject || "",
            crossingType: point.crossingType || "",
            voltageLevel: project?.voltageLevel || "220kV",
            spanLength: point.spanLength?.toString() || "",
            crossingHeight: point.crossingHeight?.toString() || "",
            groundClearance: point.groundClearance?.toString() || "",
            windSpeed: point.windSpeed?.toString() || "",
            iceThickness: point.iceThickness?.toString() || "",
            name: `${point.name}施工方案`,
          }));
        }
      }
    } catch (error) {
      console.error("加载数据失败:", error);
    }
    setIsLoading(false);
  };

  const updateSchemeData = (newData) => {
    setSchemeData((prev) => ({ ...prev, ...newData }));
  };

  const nextStep = () => {
    if (currentStep < 5) {
      setCurrentStep(currentStep + 1);
    }
  };

  const prevStep = () => {
    if (currentStep > 1) {
      setCurrentStep(currentStep - 1);
    }
  };

  const handleSubmit = async () => {
    try {
      // 准备提交数据
      const submitData = {
        crossingPointId: schemeData.crossingPointId,
        name: schemeData.name,
        version: schemeData.version,
        constructionMethod: schemeData.constructionMethod,
        methodReasoning: schemeData.methodReasoning,
        constructionSteps: schemeData.constructionSteps,
        totalDuration: schemeData.constructionSteps.reduce(
          (sum, step) => sum + (step.durationDays || 0),
          0
        ),
        approvalStatus: "draft",
      };

      await ConstructionSchemeAPI.create(submitData);
      navigate(createPageUrl("ConstructionSchemes"));
    } catch (error) {
      console.error("创建施工方案失败:", error);
    }
  };

  const renderCurrentStep = () => {
    switch (currentStep) {
      case 1:
        return (
          <ProjectInfoStep
            data={schemeData}
            onUpdate={updateSchemeData}
            projects={projects}
            crossingPoints={crossingPoints}
          />
        );
      case 2:
        return (
          <MeasurementDataStep data={schemeData} onUpdate={updateSchemeData} />
        );
      case 3:
        return (
          <ConstructionMethodStep
            data={schemeData}
            onUpdate={updateSchemeData}
          />
        );
      case 4:
        return (
          <SchemeDetailStep data={schemeData} onUpdate={updateSchemeData} />
        );
      case 5:
        return (
          <PreviewConfirmStep
            data={schemeData}
            crossingPoints={crossingPoints}
            projects={projects}
          />
        );
      default:
        return null;
    }
  };

  if (isLoading) {
    return <div className="p-6">加载中...</div>;
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-4xl mx-auto p-6">
        <div className="mb-6">
          <Button
            variant="ghost"
            onClick={() => navigate(createPageUrl("ConstructionSchemes"))}
            className="mb-4"
          >
            <ArrowLeft className="w-4 h-4 mr-2" />
            返回
          </Button>

          <div>
            <h1 className="text-2xl font-bold text-gray-900 mb-2">
              创建施工方案
            </h1>
            <p className="text-gray-600">智能生成高压输电线路跨越施工方案</p>
          </div>
        </div>

        <WizardHeader currentStep={currentStep} />

        <Card className="mt-6">
          <CardContent className="p-8">{renderCurrentStep()}</CardContent>
        </Card>

        <div className="flex justify-between mt-6">
          <Button
            variant="outline"
            onClick={prevStep}
            disabled={currentStep === 1}
          >
            <ArrowLeft className="w-4 h-4 mr-2" />
            上一步
          </Button>

          {currentStep < 5 ? (
            <Button onClick={nextStep}>
              下一步
              <ArrowRight className="w-4 h-4 ml-2" />
            </Button>
          ) : (
            <div className="flex gap-3">
              <Button variant="outline">
                <Download className="w-4 h-4 mr-2" />
                完成并生成文档
              </Button>
              <Button onClick={handleSubmit}>创建方案</Button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
